package com.example.redisspringboot;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.Set;

public class RedisDemo {

    public static void test1(Jedis jedis){
        System.out.println("get 和 set");
        //先清空数据库 避免上一次测试影响下一次测试的结果
        jedis.flushAll();

        jedis.set("key","111");
        jedis.set("key2","222");
        SetParams setParams = new SetParams();
        setParams.ex(10);
        setParams.nx();
        jedis.set("key3","333",setParams);
        String value = jedis.get("key3");
        System.out.println("value = " +  value);
    }

    public static void test2(Jedis jedis){
        System.out.println("exists 和 del");
        jedis.flushAll();

        jedis.set("key","111");
        jedis.set("key2","222");

        Boolean result = jedis.exists("key");
        System.out.println("result:" + result);
    }

    public static void test3(Jedis jedis){
        System.out.println("keys");
        jedis.flushAll();

        jedis.set("key","111");
        jedis.set("key2","222");
        jedis.set("key3","333");
        jedis.set("key4","444");

        Set<String> keys = jedis.keys("*");
        System.out.println(keys);
    }

    public static void test4(Jedis jedis){
        System.out.println("expire 和 ttl");
        jedis.flushAll();
        jedis.set("key","111");
        jedis.expire("key",10);

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Long time = jedis.ttl("key");
        System.out.println("time:"+time);
    }

    public static void test5(Jedis jedis){
        System.out.println("type");
        jedis.flushAll();

        jedis.set("key","111");
        String type = jedis.type("key");
        System.out.println("type:" + type);

        jedis.lpush("key2","111","222","333");
        type = jedis.type("key2");
        System.out.println(type);

        jedis.hset("key3","f1","111");
        type = jedis.type("key3");
        System.out.println(type);

        jedis.sadd("key4","111","222","333");
        type = jedis.type("key4");
        System.out.println(type);

        jedis.zadd("key5",10,"zhangsan");
        type = jedis.type("key5");
        System.out.println("type:" + type);
    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try(Jedis jedis = jedisPool.getResource()){
            jedis.auth("123456");
            //redis 的各种命令 对应到jedis对象的各种方法
//            String pong = jedis.ping();
//            System.out.println(pong);
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
//            test4(jedis);
            test5(jedis);
        }
    }
}
